<?php
class CjModel extends Model {
	// 分页采集跳转
	public function jump($page, $pagemax, $pagelink){
		if($page < $pagemax){
			//缓存断点续采并跳转到下一页
			$jumpurl = str_replace('FFLINK',($page+1), $pagelink);
			F('_cj/xucai',$jumpurl);
			echo '<meta http-equiv="refresh" content='.C('collect_time').';url='.$jumpurl.'>';
			echo '<h5>'.C('collect_time').'秒后将自动采集下一页!</h5>';
		}else{
			//清除断点续采
			F('_cj/xucai',NULL);
			echo '<h5>恭喜您，所有采集任务已经完成。</h5>';
		}
	}
	//视频库采集
	public function vod($admin, $params){
        /**
         * admin: array(8) { ["cjid"]=> string(2) "16" ["cjtype"]=> string(1) "1" ["action"]=> string(4) "show" ["xmlurl"]=> string(52) "aHR0cDovL3d3dy56ZHppeXVhbi5jb20vaW5jL2ZlaWZlaTMuNC8="
         * ["xmltype"]=> string(4) "json" ["field"]=> NULL ["apikey"]=> NULL ["page"]=> int(1) }
         * params:  array(6) { ["h"]=> NULL ["cid"]=> NULL ["inputer"]=> NULL ["play"]=> NULL ["wd"]=> string(3) "DVD" ["limit"]=> NULL }
         */
		$params['g'] = 'plus';
		$params['m'] = 'api';
		$params['a'] = 'json';
		$params['p'] = $admin['page'];
		$params['key'] = $admin['apikey'];
		ksort($params);
		$url = base64_decode($admin['xmlurl']).'?'.http_build_query($params);
		if($admin['xmltype'] == 'xml'){
			return $this->vod_xml($admin, $params);
		}elseif($admin['xmltype'] == 'json'){
			return $this->vod_json($admin, $params);
		}else{
			$data = $this->vod_json($admin, $params);
			if($data['status'] == 200){
				return $data;
			}else{
				return $this->vod_xml($admin, $params);
			}
		}
	}
	private function vod_json($admin, $params){
		$url = base64_decode($admin['xmlurl']).'?'.http_build_query($params);
		$html = ff_file_get_contents($url);
		//是否采集到数据
		if(!$html){
			return array('status'=>601, 'infos'=>'连接API资源库失败，通常为服务器网络不稳定或禁用了采集。');
		}
		//数据包验证
		$json = json_decode($html, true);
		if( is_null($json) ){
			return array('status'=>602, 'type'=>'json', 'infos'=>'JSON格式不正确，不支持采集。');
		}
		//资源库返回的状态501 502 503 3.3版本前没有status字段
		if($json['status'] && $json['status'] != 200){
			return array('status'=>$json['status'], 'type'=>'json', 'infos'=>$json['data']);
		}
		//不是feifeicms的格式
		if(!$json['list']){
			return array('status'=>602, 'type'=>'json', 'infos'=>'不是FeiFeiCms系统的接口，不支持采集。');
		}

		foreach ($json['data'] as $k=>$v){
		    $json['data'][$k]['vod_name'] = ff_replace_vname($json['data'][$k]['vod_name'] );
        }

		//返回正确的数据集合
		return array('status'=>200, 'type'=>'json', 'infos'=>$json);
	}
	private function vod_xml($admin, $params){
		return $this->vod_xml_caiji($admin, $params);
	}
	public function vod_update($admin, $params, $json){
        /**
         * $params:
         * array(7) { ["h"]=> NULL ["cid"]=> NULL ["inputer"]=> NULL ["play"]=> NULL ["wd"]=> string(9) "大黄蜂" ["limit"]=> NULL ["vodids"]=> string(6) "141326" }
         */

		echo'<style type="text/css">
			ul{margin:0 auto; width:60%;border:1px solid #666;}
			h5{text-align:center;}
			li{font-size:12px;color:#333;line-height:21px}
			li.p{color:#666;list-style:none;}
			span{font-weight:bold;color:#FF0000}
			</style><ul>
			<h5>API视频采集 共有<span>'.$json['page']['recordcount'].'</span>个数据，需要采集<span>'.$json['page']['pagecount']
            .'</span>次，正在执行第<span color=green>'.$admin['page'].'</span>次采集任务，每一次采集<span>'.$json['page']['pagesize'].'</span>个。</h5>';
		// 重采资料或是采集入库
		if($admin['field']){
			$field = explode(',',$admin['field']);
			foreach($json['data'] as $key=>$vod){
				$data = array();
				foreach($field as $keyfield=>$value){
					$data[$value] = $vod[$value];
				}
				$status = $this->vod_db_field($data, $vod['vod_reurl']);
				if($status){
					echo '<li>重采['.ff_list_find($vod['vod_cid']).'] '.$vod['vod_name'].' '.$array_url['field'].'更新完成。</li>';
				}else{
					echo '<li>重采['.ff_list_find($vod['vod_cid']).'] '.$vod['vod_name'].' 跳过、不做任何处理。</li>';
				}
				ob_flush();flush();
			}
		}else{
			foreach($json['data'] as $key=>$vod){
                if($vod['vod_year']){
                    if($vod['vod_year']>date('Y')){
                        echo '<li>第<span>'.(($admin['page']-1)*$json['page']['pagesize']+$key+1).'</span>个影片 ['.ff_list_find($vod['vod_cid']).'] '.$vod['vod_name'].'_'.($vod['vod_year']).'超过当前年份</li>';
                        continue;
                    }
                }
                if($vod['d_year']){
                    if($vod['d_year']>date('Y')){
                        echo '<li>第<span>'.(($admin['page']-1)*$json['page']['pagesize']+$key+1).'</span>个影片 ['.ff_list_find($vod['vod_cid']).'] '.$vod['vod_name'].'_'.($vod['d_year']).'超过当前年份</li>';
                        continue;
                    }
                }

				echo '<li>第<span>'.(($admin['page']-1)*$json['page']['pagesize']+$key+1).'</span>个影片 ['.ff_list_find($vod['vod_cid']).'] '.$vod['vod_name'].'_'.($vod['vod_year']?$vod['vod_year']:$vod['d_year']).'</li>';
				$vod['vod_inputer'] = 'xml_'.$admin['cjid'];
				$vod['vod_name'] = ff_replace_vname($vod['vod_name']);

				$this->vod_db($vod);
				ob_flush();flush();
                //sleep(1);
			}
		}
		//是否分页采集
		if( in_array($admin['action'], array('days','all','post')) ){
			$admin['g'] = 'admin';
			$admin['m'] = 'cj';
			$admin['a'] = 'apis';
			$admin['page'] = 'FFLINK';
			$page_link = '?'.http_build_query(array_merge($admin, $params));
			$this->jump($json['page']["pageindex"], $json['page']['pagecount'], $page_link);
		}
		echo'</ul>';
	}
	//视频采集入库调用接口，必需要有vod_reurl字段
	public function vod_db($vod){
		//去除资源站视频ID与写入资源站编辑标识
		$vod["vod_id"] = null;
		//必填字段验证
		if(empty($vod['vod_name']) || empty($vod['vod_url']) || empty($vod['vod_play'])){
			echo '<li class="p">影片名称['.$vod['vod_name'].']或播放器名称['.$vod['vod_play'].']或播放地址['.$vod['vod_url'].']为空，不做处理!</li>';
			return false;
		}
		//是否绑定分类验证
		if(!$vod['vod_cid']){
			echo '<li class="p">未匹配到对应栏目分类，不做处理，请先转换分类!</li>';
			return false;
		}
		//来源标识验证
		if(!$vod['vod_reurl']){
			echo '<li class="p">来源标识为空，不做处理!</li>';
			return false;
		}

        // 播放器处理（去掉未定义或隐藏的播放器）
        $play_list_db = $this->vod_array2url($this->vod_url2array($vod['vod_play'], $vod['vod_url']));
        if(!$play_list_db["vod_play"]){
            echo '<li class="p">播放来源('.$vod['vod_play'].')未添加或隐藏，此影片跳过！</li>';
            return false;
        }

        $vod = $this->vod_douban_info($vod);
		$vyear = $vod['vod_year']?$vod['vod_year']:$vod['d_year'];
//		if(!$vod['vod_douban_id']){
//		    echo '<li class="p"><strong>未获得豆瓣信息：</strong>'.$vod['vod_name'].'_'.$vyear.'失败</li>';
//		    return false;
//        }

//		if(!$vod['vod_douban_score']|| $vod['vod_douban_score'] == '' || $vod['vod_douban_score']<=1 ){
//            echo '<li class="p"><strong>豆瓣评分低于1，不收录电影：</strong>'.$vod['vod_name'].'</li>';
//            return ;
//        }
        if(strpos($vod['vod_url'],'haku99.com')!==false) {
            $vod['vod_url'] = str_replace('haku99.com', 'haku88.com', $vod['vod_url']);
        }
		//3.5后改为一次性修改不再单独一个一个检查
		$array_vod_old = $this->vod_db_find($vod);
		if($array_vod_old['vod_id']){
		    // 不再推送到百度
		    //ff_push_url_to_baidu(array('http://www.ffilmer.com/video/detail/'.$array_vod_old['vod_id'].'.html'));
			$status = '<li class="p"><strong>编辑：</strong>'.$this->vod_db_update($vod, $array_vod_old).' - '.$array_vod_old['vod_id'].'</li>';
		}else{

			$status = '<li class="p"><strong>新增：</strong>'.$this->vod_db_insert($vod).'</li>';
		}
		echo $status;
	}
	//检测是否已存在相同影片
	private function vod_db_find($vod){

        /**
         * vod:
         *array(34) { ["vod_cid"]=> int(2) ["vod_name"]=> string(9) "老中医" ["vod_title"]=> string(0) "" ["vod_type"]=> string(0) "" ["vod_keywords"]=> string(0) ""
         * ["vod_actor"]=> string(36) "陈宝国,冯远征,许晴,陈月末" ["vod_director"]=> string(9) "毛卫宁"
         * ["vod_content"]=> string(482) "《老中医》以1927年—1946年间的上海为背景，讲述江苏常州孟河医派传人翁泉海闯荡上海滩，倾尽一生致力于中医文化的保护与传承的故事。
         * 该剧旨在以小人物经历体现大历史格局，来展现传统中医文化的无穷魅力，以及中医传承数千年，且历久弥新的强大生命力，讴歌了中国人民在传统文化的滋养下，坚韧不拔、勤劳守信、
         * 宽厚仁爱、不畏强权的民族精神特质。" ["vod_pic"]=> string(62) "https://img.yongjiu7.com/upload/vod/2019-02-22/15508430699.jpg" ["vod_area"]=> string(6) "大陆"
         * ["vod_language"]=> NULL ["d_year"]=> string(4) "2019" ["vod_addtime"]=> string(19) "2019-03-08 12:21:57" ["vod_filmtime"]=> int(0) ["vod_server"]=> string(0) ""
         * ["vod_play"]=> string(14) "yjyun$$$yjm3u8" ["vod_url"]=> string(3617) "第01集$https://yoube.bili-yongjiu.com/share/n81lO3QtdLnMxdyG
         * 第02集$https://yoube.bili-yongjiu.com/share/RSjI5LZhJQ7fCFPb 第03集$https://yoube.bili-yongjiu.com/share/JnUNYGrUUqXT7sQ2 第04集第27集$https://yoube.bili-yongjiu.com/20190308/TqoG77lc/index.m3u8"
         * ["vod_inputer"]=> string(6) "xml_14" ["vod_reurl"]=> string(52) "http://www.yongjiuzy.com/?m=vod-detail-id-19251.html" ["vod_length"]=> int(0)
         * ["vod_weekday"]=> NULL ["vod_copyright"]=> int(0) ["vod_state"]=> string(0) "" ["vod_version"]=> string(0) "" ["vod_tv"]=> string(0) "" ["vod_total"]=> int(0)
         * ["vod_continu"]=> string(2) "27" ["vod_status"]=> int(1)
         * ["vod_stars"]=> int(0) ["vod_hits"]=> NULL ["vod_isend"]=> int(1) ["vod_douban_id"]=> int(0) ["vod_series"]=> string(0) "" ["list_name"]=> string(9) "国产剧" }
         *
         */

		// 要查询检查的字段
		$field = 'vod_id,vod_cid,vod_douban_id,vod_name,vod_year,vod_title,vod_actor,vod_continu,vod_isend,vod_total,vod_inputer,vod_play,vod_url,vod_reurl';

		// 按标题长度检测 大于3个字符才检测 (需防止同名的电影与电视冲突所以增加了CID条件)
			//$vod_name_length = mb_strwidth($vod['vod_name'],'utf-8');
			//$vod_name_like = @mb_strimwidth($vod['vod_name'], 0, intval(C('collect_name'))*2, '', 'utf-8');
			//$vod_name_like = $vod['vod_name'];
			//var_dump($vod_name_like);exit();
			//if($vod_name_like) {
        $where = array();
        if($vod['vod_id']){
            $where['vod_id'] = array('eq', $vod['vod_id']);
        }else if($vod['vod_douban_id']){
            $where['vod_douban_id'] = array('eq', $vod['vod_douban_id']);
        }else{
            return $vod;
        }

        $array = M('Vod')->field($field)->where($where)->order('vod_id desc')->find();

        if($array){
            return $array;
        }

        // 按来源检测是否完全相同
        $array = M('Vod')->field($field)->where('vod_reurl like "%'.$vod['vod_reurl'].'%"')->order('vod_id desc')->find();
        if($array){
            return $array;
        }
			//}
		return $vod;
	}
	//新增影片
	private function vod_db_insert($vod){
	    $vod['vod_name'] = ff_replace_vname($vod['vod_name']);
		$vod['vod_letter'] 	= ff_url_letter($vod['vod_name']);
		$vod['vod_keywords'] 	= trim($vod['vod_keywords']);

        $vod['vod_year'] = $vod['vod_year']>date("Y")?date("Y"):$vod['vod_year'];

		if(empty($vod['vod_ename'])){
			$vod['vod_ename'] = ff_pinyin($vod['vod_name']);
		}
		if(empty($vod['vod_hits'])){
			$vod['vod_hits'] = mt_rand(0, C('collect_hits'));
		}
		if(empty($vod['vod_up'])){
			$vod['vod_up'] = mt_rand(0, C('collect_updown'));
		}
		if(empty($vod['vod_down'])){
			$vod['vod_down'] = mt_rand(0, C('collect_updown'));
		}
		if( empty($vod['vod_gold']) ){
			$vod['vod_gold'] = mt_rand(0, C('collect_gold'));
		}
		if( empty($vod['vod_golder']) ){
			$vod['vod_golder'] = mt_rand(0, C('collect_golder'));
		}
        if( empty($vod['vod_filmtime']) ){
            if($vod['vod_year']){
                if(strlen($vod['vod_year'])==4 ){
                    $vod['vod_filmtime'] = strtotime($vod['vod_year'].'-01-01');
                }

            }else{
                $vod['vod_filmtime'] = strtotime('1800-01-01');
            }

        }else if(strlen($vod['vod_filmtime'])==4 ){
            $vod['vod_filmtime'] = strtotime($vod['vod_filmtime'].'-01-01');
        }

		if( empty($vod['vod_addtime']) ){
			$vod['vod_addtime'] = time();
		}else{
			$vod['vod_addtime'] = strtotime($vod['vod_addtime']);
		}
		// 播放器处理（去掉未定义或隐藏的播放器）
		$play_list_db = $this->vod_array2url($this->vod_url2array($vod['vod_play'], $vod['vod_url']));
		if(!$play_list_db["vod_play"]){
			return '播放来源('.$vod['vod_play'].')未添加或隐藏，此影片跳过！';
		}
		$vod['vod_play'] = $play_list_db['vod_play'];
		$vod['vod_url'] = $play_list_db['vod_url'];
		unset($play_list_db);
		// 随机伪原创
		if(C('collect_original')){
			$vod['vod_content'] = ff_rand_str($vod['vod_content']);
		}
		// 自动下载远程图片
		$vod['vod_pic'] = D('Img')->down_load($vod['vod_pic']);

		// 视频入库
		$id = M('Vod')->data($vod)->add();

		// 关联多分类及TAG相关
		if($id){
            // 不再推送到baidu
            //ff_push_url_to_baidu(array('http://www.ffilmer.com/video/detail/'.$id.'.html'));

			// 自动获取关键词tag
			if(empty($vod['vod_keywords']) && C('collect_tags')){
				$vod['vod_keywords'] = ff_tag_auto($vod["vod_name"], $vod["vod_content"]);
			}
			// 增加关联tag
			if( $vod['vod_keywords'] ){
				D('Tag')->tag_update($id, $vod["vod_keywords"], 'vod_tag');
			}
			// 增加多分类
			if( $vod['vod_type'] ){
				D('Tag')->tag_update($id, $vod["vod_type"], 'vod_type');
			}
			return '视频添加成功('.$id.')';
		}
		return '视频添加失败：'.M('Vod')->getDbError();
	}
	//根据影片ID更新数据
	private function vod_db_update($vod, $vod_old){
		// 检测是否站长手动锁定更新
		if('feifeicms' == $vod_old['vod_inputer']){
			return '站长已锁定该影片，不更新。';
		}
		// 检测播放地址是否变化
		$play_list_old = $this->vod_url2array($vod_old['vod_play'], $vod_old['vod_url']);
		$play_list_new = $this->vod_url2array($vod['vod_play'], $vod['vod_url']);
		$play_list_merge = array_merge($play_list_old, $play_list_new);//合并新旧地址
		$play_list_db = $this->vod_array2url($play_list_merge);//还原入库字段

		if( $vod['vod_reurl'] && strpos($vod_old['vod_reurl'] , $vod['vod_reurl'])!==false
            && ( !$vod['vod_douban_id'] || $vod_old['vod_douban_id'] == $vod['vod_douban_id'] ) && $vod_old['vod_url'] == $play_list_db['vod_url']){
			return '<font color="blue">播放地址未变化，不需要更新</font>';
		}

        $vod['vod_year'] = $vod['vod_year']>date('Y')?date('Y'):$vod['vod_year'];
		// 组合更新条件及内容(以最后一次更新的库为检测依据)
		$edit['vod_id'] = $vod_old['vod_id'];
		//$edit['vod_addtime'] = time();
		//$edit['vod_name'] = ff_replace_vname($vod['vod_name']);
        $edit['vod_cid'] = $vod['vod_cid'];
		$edit['vod_inputer'] = $vod['vod_inputer'];

		if($vod_old['vod_reurl']==null || !$vod_old['vod_reurl']){
            $edit['vod_reurl'] = $vod['vod_reurl'];
        }else if(strpos($vod_old['vod_reurl'],$vod['vod_reurl'])===false ){
            $edit['vod_reurl'] = $vod_old['vod_reurl'] .'|'. $vod['vod_reurl'];
        }else{
            $edit['vod_reurl'] = $vod_old['vod_reurl'];
        }

		$edit['vod_play'] = $play_list_db['vod_play'];
        if($vod_old['vod_url'] != $play_list_db['vod_url']){
            $edit['vod_url'] = $play_list_db['vod_url'];
        }
        if($vod['vod_douban_id'] && $vod_old['vod_douban_id'] != $vod['vod_douban_id']  ){
            $edit['vod_douban_id'] = $vod['vod_douban_id'];
        }

		// 存在的字段才更新
		if(isset($vod['vod_total'])){
			$edit['vod_total'] = $vod['vod_total'];
		}
		if(isset($vod['vod_continu'])){
			$edit['vod_continu'] = $vod['vod_continu'];
		}
		if(isset($vod['vod_isend'])){
			$edit['vod_isend'] = $vod['vod_isend'];
		}

        if( empty($vod['vod_addtime']) ){
            $vod['vod_addtime'] = time();
        }else{
            $vod['vod_addtime'] = strtotime($vod['vod_addtime']);
        }
        if(isset($vod['vod_filmtime']) && $vod['vod_filmtime'] > 0 ){
            $edit['vod_filmtime'] = $vod['vod_filmtime'];
        }
        if(isset($vod['vod_douban_score'])){
            $edit['vod_douban_score'] = $vod['vod_douban_score'];
        }
		if(isset($vod['vod_year'])){
			$edit['vod_year'] = $vod['vod_year'];
		}
//		if(isset($vod['vod_length'])){
//			$edit['vod_length'] = $vod['vod_length'];
//		}
		if(isset($vod['vod_state'])){
			$edit['vod_state'] = $vod['vod_state'];
		}
		if(isset($vod['vod_version'])){
			$edit['vod_version'] = $vod['vod_version'];
		}
		if(isset($vod['vod_tv'])){
			$edit['vod_tv'] = $vod['vod_tv'];
		}
		// 更新数据
		M('Vod')->data($edit)->save();
		//删除数据缓存
		if(C('cache_page_vod')){
			S(md5('cache_page_vod_'.$vod_old['vod_id']),NULL);
		}
		return '<font color="red">旧播放地址已更新</font>';
	}
	//根据来源地址更新资料字字段
	private function vod_db_field($vod, $reurl){
		if($vod['vod_pic']){
			$vod['vod_pic'] = D('Img')->down_load($vod['vod_pic']);
		}
		return M('Vod')->where("vod_inputer !='feifeicms' and vod_reurl like '%".$reurl."%'")->data($vod)->save();
	}
	//vod_play,vod_url格式化：所有播放地址定义为普通数组便于合并 url['youku(playname)-1(sid)-6(jid)'] = 'xxxx'
	private function vod_url2array($vod_play, $vod_url){
		$old_play = explode('$$$',$vod_play);
		$old_url = explode('$$$',$vod_url);
		$old_array = array();
		$sid = array();
		foreach($old_play as $key=>$value){
			$url_one = explode( chr(13), str_replace(array("\r\n", "\n", "\r"), chr(13), $old_url[$key]) );
			foreach($url_one as $key_son=>$value_son){
				$old_array[$value.'-'.intval($sid[$value]).'-'.$key_son] = $value_son;
			}
			$sid[$value] = +1;// 有两组PPTV的情况
		}
		return $old_array;
	}
	//vod_play,vod_url字段还原：将数组定义的所有播放地址还原
	private function vod_array2url($play_list_merge){
		foreach($play_list_merge as $key=>$value){
			list($play_name,$play_sid,$play_pid) = explode('-',$key);
			$play[$play_name.$play_sid] = $play_name;
			$array_url[$play_name.$play_sid][$play_pid] = $value;
		}
		//还原单组播放地址
		foreach($array_url as $key=>$value){
			$url[$key] = implode(chr(13),$value);
		}
		//只添加已定义的播放器
		$array_player = F('_feifeicms/player');
		foreach($play as $key=>$value){
			if(!$array_player[$value]){
				unset($play[$key]);
				unset($url[$key]);
			}
		}
		return array('vod_play'=>implode('$$$',$play),'vod_url'=>implode('$$$',$url));
	}
	//xml资源库采集
	private function vod_xml_caiji($admin, $params){
		$url = array();
		if($admin['action']=='show' && $params['wd']){
			$url['ac'] = 'list';
		}else{
			$url['ac'] = 'videolist';
		}
		$url['wd'] = $params['wd'];
		$url['t'] = $params['cid'];
		$url['h'] = $params['h'];
		$url['rid'] = $params['play'];
		$url['ids'] = $params['vodids'];
		$url['pg'] = $admin['page'];
		$url_detail = base64_decode($admin['xmlurl']).'?'.http_build_query($url);
		$url_list   = base64_decode($admin['xmlurl']).'?ac=list&t=9999';

        /**
         * url_detail:  http://www.kukuzy.com/inc/api.php?ac=videolist&wd=%E5%A4%A7%E9%BB%84%E8%9C%82&ids=141326&pg=1
         */

		$xml_detail = ff_file_get_contents($url_detail);
		if(!$xml_detail){
			return array('status'=>601, 'infos'=>'连接API资源库失败，通常为服务器网络不稳定或禁用了采集。');
		}
		$xml = simplexml_load_string($xml_detail);
		if( is_null($xml) ){
			return array('status'=>602, 'type'=>'xml', 'infos'=>'XML格式不正确，不支持采集。');
		}
		$key = 0;
		$array_vod = array();
		foreach($xml->list->video as $video){

		    if($video->pic_slide){echo 'pic_slide == '.$video->pic_slide; }
            if($video->pic_bg){echo 'pic_bg == '.$video->pic_bg; }

			$array_vod[$key]['vod_id'] = (string)$video->id;
			$array_vod[$key]['vod_cid'] = (string)$video->tid;

			$vname = (string)$video->name;   //  ff_replace_vname((string)$video->name);

			$array_vod[$key]['vod_name'] = $vname;
			$array_vod[$key]['vod_title'] = (string)$video->note;
			$array_vod[$key]['list_name'] = (string)$video->type;
			$array_vod[$key]['vod_pic'] = (string)$video->pic;
			$array_vod[$key]['vod_language'] = (string)$video->lang;
			$array_vod[$key]['vod_area'] = (string)$video->area;
			$array_vod[$key]['vod_year'] = (string)($video->year>date('Y')?date('Y'):$video->year);
			$array_vod[$key]['vod_continu'] = (string)$video->state;
			$array_vod[$key]['vod_actor'] = (string)$video->actor;
			$array_vod[$key]['vod_director'] = (string)$video->director;
			$array_vod[$key]['vod_content'] = (string)$video->des;
			$array_vod[$key]['vod_reurl'] = base64_decode($admin['xmlurl']).'?id='.(string)$video->id;
			$array_vod[$key]['vod_status'] = 1;
			$array_vod[$key]['vod_type'] = str_replace('片','',$array_vod[$key]['list_name']);
			$array_vod[$key]['vod_addtime'] = (string)$video->last;
			$array_vod[$key]['vod_total'] = 0;
			$array_vod[$key]['vod_isend'] = 1;
			if($array_vod[$key]['vod_continu']){
				$array_vod[$key]['vod_isend'] = 0;
			}
			//格式化地址与播放器
			$array_play = array();
			$array_url = array();
			//videolist|list播放列表不同
			if($count=count($video->dl->dd)){
				for($i=0; $i<$count; $i++){
					$array_play[$i] = str_replace('qiyi','iqiyi',(string)$video->dl->dd[$i]['flag']);
					$array_url[$i] = $this->vod_xml_replace((string)$video->dl->dd[$i]);
				}
			}else{
				$array_play[]=(string)$video->dt;
			}
			$array_vod[$key]['vod_play'] = implode('$$$', $array_play);
			$array_vod[$key]['vod_url'] = implode('$$$', $array_url);
			$key++;
		}

		// array_vod :
        /***
         * array(1) { [0]=> array(21) {
         *   ["vod_id"]=> string(6) "141326" ["vod_cid"]=> string(1) "5" ["vod_name"]=> string(40) "大黄蜂/变形金刚外传：大黄蜂"
         *   ["vod_title"]=> string(13) "HD1080P中字" ["list_name"]=> string(9) "动作片" ["vod_pic"]=> string(56) "https://www.605zy.com/upload/vod/2018-12/15450203111.jpg"
         *   ["vod_language"]=> string(6) "英语" ["vod_area"]=> string(6) "欧美" ["vod_year"]=> string(4) "2018" ["vod_continu"]=> string(1) "0"
         *   ["vod_actor"]=> string(83) "海莉·斯坦菲尔德,约翰·塞纳,小豪尔赫·兰登伯格,杰森·德鲁克" ["vod_director"]=> string(20) "特拉维斯·奈特"
         *   ["vod_content"]=> string(244) "本片故事设定在1987年，正值青春期的18岁少女查理Charlie（海莉·斯坦菲尔德 饰）在加州海边小镇的废弃场里发现了伤痕累累的大黄蜂，
         * 他们之间会发生怎样的故事呢？让我们拭目以待！" ["vod_reurl"]=> string(43) "http://www.kukuzy.com/inc/api.php?id=141326" ["vod_status"]=> int(1)
         *  ["vod_type"]=> string(6) "动作" ["vod_addtime"]=> string(19) "2019-01-21 11:41:30" ["vod_total"]=> int(0) ["vod_isend"]=> int(1)
         *  ["vod_play"]=> string(16) "605yun$$$605m3u8" ["vod_url"]=> string(287) "HD1080P中字$https://www.605yunpan.com/play/index/6727508c0c1c HD1080P中字
         * $https://www.ziyuan605.com/share/kSyDoH4C034PGjC1$$$HD1080P中字$https://605pan.www605zy.com/video/m3u8/201901/19/6727508c0c1c/playlist.m3u8 HD1080P中字
         * $https://www.ziyuan605.com/20190119/uYWk7LiP/index.m3u8" } }
         */

		//分页信息
		preg_match('<list page="([0-9]+)" pagecount="([0-9]+)" pagesize="([0-9]+)" recordcount="([0-9]+)">', $xml_detail, $page_array);
		$array_page = array('pageindex'=>$page_array[1], 'pagecount'=>$page_array[2], 'pagesize'=>$page_array[3], 'recordcount'=>$page_array[4]);
		//栏目分类
		$array_list = array();
		if($admin['action'] == 'show'){
			$xml = simplexml_load_string(ff_file_get_contents($url_list));
			$key = 0;
			foreach($xml->class->ty as $list){
				$array_list[$key]['list_id'] = (int)$xml->class->ty[$key]['id'];
				$array_list[$key]['list_name'] = (string)$list;
				$key++;
			}
		}
		return array('status'=>200,'type'=>'xml', 'infos'=>array('page'=>$array_page,'list'=>$array_list,'data'=>$array_vod));
	}

	private function vod_douban_info($vod){

        $doubanSuggestUrl = 'https://movie.douban.com/j/subject_suggest?q=';
        $doubanDetailUrl = 'https://movie.douban.com/subject/';
        $doubanSearchUrl = 'https://www.douban.com/search?cat=1002&q=';

        $dacuoKeys2 = explode(',', C('apikey_douban2'));

        $infos = array();

        // 根据影片名称筛选
        $arrdx1 = array('第十一', '第十二', '第十三', '第十四', '第十五', '第十六', '第十七', '第十八', '第十九', '第十', '第一', '第二', '第三', '第四', '第五', '第六', '第七', '第八', '第九');
        $arrxx1 = array('第11', '第12', '第13', '第14', '第15', '第16', '第17', '第18', '第19', '第10', '第1', '第2', '第3', '第4', '第5', '第6', '第7', '第8', '第9');

        // 不能有空格
        $vod['vod_name'] = str_replace(' ','', $vod['vod_name']);
        $name_nodakuohu = preg_replace('/\[.+?\]/', '', $vod['vod_name']);
        $name_noxiaokuohu = preg_replace('/（.+?）/', '', $vod['vod_name']);

        $name_nohanju = str_replace('[韩剧]', '', $vod['vod_name']);
        $name_nohanju = str_replace('韩剧', '', $name_nohanju);

        $name_notaiju = str_replace('[泰剧]', '', $vod['vod_name']);
        $name_notaiju = str_replace('泰剧', '', $name_notaiju);

        $name_notaiban = str_replace('[台版]', '', $vod['vod_name']);
        $name_notaiban = str_replace('台版', '', $name_notaiban);

        $name_nogangban = str_replace('[港版]', '', $vod['vod_name']);
        $name_nogangban = str_replace('港版', '', $name_nogangban);

        $name_noshanjian1 = str_replace('未删减版', '', $name_nogangban);
        $name_noshanjian2 = str_replace('未删减', '', $name_nogangban);

        $name_noguoyu = str_replace('国语', '', $name_nogangban);

        $arrnames = explode('/', $vod['vod_name']);

        // 对影片名称进行处理，去掉各种额外的文字、符号等，尽量得到正确的影片名称
        $vnames = array($vod['vod_name'], $name_noshanjian1,$name_noguoyu, $name_noshanjian2, $name_nodakuohu, $name_noxiaokuohu, $name_nohanju, $name_notaiju, $name_notaiban, $name_nogangban, str_replace($arrxx1, $arrdx1, $vod['vod_name']));

        foreach ($arrnames as $ka => $va) {
            $vnames[] = $va;
        }
        $vnames = array_unique($vnames);


        $v1year = $vod['vod_year'] ? $vod['vod_year'] : $vod['d_year'];
        
        if($v1year>date('Y')){
            $v1year = date('Y');
        }

        $proxy = C('proxy');

        if($proxy!=null && $proxy!='') {
            $arrProxy = explode(":", $proxy);
        }else{
            $arrProxy=['https','142.93.44.189','3128'];
        }

        // 根据vod_reurl 筛选影片
        $vod3 = M('Vod')->where('vod_reurl like \'%'.$vod['vod_reurl'].'%\'  ')->find();
        // 之前没有抓取过该资源的内容
        if(!$vod3) {

            // 首先从数据库查是否已经存在该影片
            foreach ($vnames as $k2 => $v2) {

                $vod3s = M('Vod')->where('vod_name=\'' . $v2 . '\' ')->select();

                foreach($vod3s as $k3 =>$vod3) {
                    if ($vod3) {

                        $v3year = $vod3['vod_year']>date('Y')?date('Y'):$vod3['vod_year']<$vod['vod_year']?$vod['vod_year']:$vod3['vod_year'];
                        $vod3['vod_year'] = $v3year;

                        if ( !$v1year || $v1year<1700 || $v3year < 1700 || abs($v1year - $v3year) == 0) {

                            // 如果是新上映的电影，且分值很低的，就重新加载；或者 filmtime时间不对的
                            $vodFilmTime = $vod3['vod_filmtime'];
                            $vodDoubanScore = $vod3['vod_douban_score'];
                            if (!$vodFilmTime) {
                                $vodFilmTime = 0;
                            }
                            $nowTime = time();

                            $strvodfilmtime = date('Y-m-d',$vod3['vod_filmtime']);

                            // 早于一个月内上映的，且豆瓣评分过低的，更新豆瓣评分；
                            if ($vod3['vod_douban_id'] && (strpos($strvodfilmtime,'-01-01') > 0 ||strpos($strvodfilmtime,'1901-') >= 0
                                    || (($nowTime - $vodFilmTime) < 30 * 24 * 3600 && $vodDoubanScore < 3))) {

                                $randIndex = (time() / 60) % (sizeof($dacuoKeys2));
                                $dacuoKey2 = $dacuoKeys2[$randIndex];
                                $dacuoUrl = "http://api.daicuo.cc/douban/?key=" . $dacuoKey2 . "&id=" . $vod3['vod_douban_id'];
                                $strDacuo = ff_file_get_contents($dacuoUrl,60, '', '', $arrProxy[0],$arrProxy[1], $arrProxy[2]);

                                $arrDacuo = json_decode($strDacuo, true);

                                if (isset($arrDacuo['data'])) {
                                    $dacuoFileTime = $arrDacuo['data']['vod_filmtime'];
                                    $dacuoDoubanScore = $arrDacuo['data']['vod_douban_score'];
                                    $dacuoYear = $arrDacuo['data']['vod_year'];
                                    $arrDacuo['data']['vod_actor'] = null;
                                    $arrDacuo['data']['vod_content'] = null;
                                }

                                if ($dacuoFileTime ) {
                                    if(strlen($dacuoFileTime) == 4){
                                        $dacuoFileTime = $dacuoFileTime.'-01-01';
                                    }
                                    if(!$vod['vod_filmtime']||strtotime($dacuoFileTime)> $vod['vod_filmtime']){
                                        $vod['vod_filmtime'] = strtotime($dacuoFileTime);
                                    }

                                }
                                if ($dacuoDoubanScore) {
                                    $vod['vod_douban_score'] = $dacuoDoubanScore;
                                }
                                if ($dacuoYear) {
                                    $vod['vod_year'] = $dacuoYear>date('Y')?date('Y'):$dacuoYear;
                                }
                            }

                            $vod['vod_id'] = $vod3['vod_id'];

                            if ($vod3['vod_douban_id']) {
                                $vod['vod_douban_id'] = $vod3['vod_douban_id'];
                            }

                            return $vod;
                        }
                    }
                }
            }

        }
        // 如果数据库中已经存在该vod_reurl 则直接获得
        else{
            $vod['vod_id'] = $vod3['vod_id'];

            if($vod3['vod_douban_id']){

                $v3year = $vod3['vod_year']>date('Y')?date('Y'):$vod3['vod_year']<$vod['vod_year']?$vod['vod_year']:$vod3['vod_year'];
                $vod3['vod_year'] = $v3year;
                $vod['vod_douban_id'] = $vod3['vod_douban_id'];

                if ($v3year > 1700 && abs($v1year - $v3year) == 0) {
                    // 如果是新上映的电影，且分值很低的，就重新加载；或者 filmtime时间不对的
                    $vodFilmTime = $vod3['vod_filmtime'];
                    $vodDoubanScore = $vod3['vod_douban_score'];
                    if (!$vodFilmTime) {
                        $vodFilmTime = 0;
                    }
                    $nowTime = time();

                    $strvodfilmtime = date('Y-m-d',$vod3['vod_filmtime']);

                    // 早于一个月内上映的，且豆瓣评分过低的，更新豆瓣评分；
                    if (strpos($strvodfilmtime,'-01-01') > 0||strpos($strvodfilmtime,'1901-') >= 0
                        || (($nowTime - $vodFilmTime) < 30 * 24 * 3600 && $vodDoubanScore < 3)) {

                        $randIndex = (time() / 60) % (sizeof($dacuoKeys2));
                        $dacuoKey2 = $dacuoKeys2[$randIndex];
                        $dacuoUrl = "http://api.daicuo.cc/douban/?key=" . $dacuoKey2 . "&id=" . $vod3['vod_douban_id'];
                        $strDacuo = ff_file_get_contents($dacuoUrl,60, '', '', $arrProxy[0],$arrProxy[1], $arrProxy[2]);

                        $arrDacuo = json_decode($strDacuo, true);

                        if (isset($arrDacuo['data'])) {
                            $dacuoFileTime = $arrDacuo['data']['vod_filmtime'];
                            $dacuoDoubanScore = $arrDacuo['data']['vod_douban_score'];
                            $dacuoYear = $arrDacuo['data']['vod_year'];
                            $arrDacuo['data']['vod_actor'] = null;
                            $arrDacuo['data']['vod_content'] = null;
                        }

                        if ($dacuoFileTime) {
                            if(strlen($dacuoFileTime)==4){
                                $dacuoFileTime = $dacuoFileTime.'-01-01';
                            }

                            if(!$vod['vod_filmtime']||strtotime($dacuoFileTime)> $vod['vod_filmtime']){
                                $vod['vod_filmtime'] = strtotime($dacuoFileTime);
                            }
                        }
                        if ($dacuoDoubanScore) {
                            $vod['vod_douban_score'] = $dacuoDoubanScore;
                        }
                        if ($dacuoYear) {
                            $vod['vod_year'] = $dacuoYear>date('Y')?date('Y'):$dacuoYear;
                        }
                    }

                    return $vod;
                }

            }

        }

        if($vod['vod_douban_id']){
            return $vod;
        }

        foreach ($vnames as $k2 => $v2) {

            $v22 = urlencode($v2);

            // 从Search地址获取电影信息

            $url3 = $doubanSearchUrl.$v22 . '&v=' . time();

            var_dump($v2.'|| proxy is == '.json_encode($arrProxy).'<br>');
            $html3 = ff_file_get_contents($url3, 60, '', '', $arrProxy[0],$arrProxy[1], $arrProxy[2]);

            if (!$html3 ){
                echo '从Search 查询结果异常,查询结果为空。'.$url3.'    <br> ';
                break;
            }

            if(strpos($html3, '到有异常请求从你的 IP 发出')>0){
                echo '从Search 查询 ，检查到有异常请求从你的 IP 发出，请采用其他代理IP。'.$url3.'  <br>';
                break;
            }

            sleep(3);

            $arrDoubanTitle = array();
            $arrDoubanYear = array();
            $arrDoubanId = array();
            $arrDoubanImg =array();

            $hasmc3 = preg_match_all("#qcat: '\d+'\}\)\" >(.+?) </a>#i",$html3,$mc3);
            if($hasmc3){
                $arrDoubanTitle = $mc3[1];
            }else{
                echo '通过search 地址未能获得title数组 '.$url3.'  ||  '.json_encode($arrProxy).' <br>';
                break;
            }

            $hasmc3 = preg_match_all("#<span class=\"subject-cast\">.+?(\d{4})</span>#i",$html3,$mc3);
            if($hasmc3){
                $arrDoubanYear = $mc3[1];
            }else{
                echo '通过search 地址未能获得year数组 '.$url3.'  ||  '.json_encode($arrProxy).' <br>';
                break;
            }

            $hasmc3 = preg_match_all("#'dou_search_movie', sid: (\d+?), qcat: '\d+'\}\)\" >#i",$html3,$mc3);
            if($hasmc3){
                $arrDoubanId = $mc3[1];
            }else{
                echo '通过search 地址未能获得id数组';
                break;
            }

            $hasmc3 = preg_match_all("#><img src=\"(.+?)\"></a>#i",$html3,$mc3);
            if($hasmc3){
                $arrDoubanImg = $mc3[1];
            }else{
                echo '通过search 地址未能获得img数组';
                break;
            }

            foreach( $arrDoubanId as $k3=>$v3 ){
                $arr3=array();
                $arr3['id']=$v3;
                $arr3['title']=$arrDoubanTitle[$k3];
                $arr3['img']=$arrDoubanImg[$k3];
                $arr3['year']=$arrDoubanYear[$k3]>date('Y')?date("Y"):$arrDoubanYear[$k3];

                $infos[] = $arr3;
            }

            if(count($infos) >0 ){
                var_dump( '从Search 获取到电影信息：title -- '.$infos[0]['title'].'  id -- '.$infos[0]['id'] .'<br>') ;
                break;
            }

        }

        if(count($infos) == 0){
            return $vod;
        }

        foreach($infos as $k1=>$v1){
            similar_text($vod['vod_name'].$v1year,$v1['title'].$v1['year'] ,$prc );
            $infos[$k1]['similar'] = $prc;
        }
        $similars = array_column($infos,'similar');
        array_multisort($similars, SORT_DESC,  $infos );

        if($infos[0]['similar']< 80 ){
            return $vod;
        }

        $doubanId = $infos[0]['id'];
        $doubanName = $infos[0]['title'];
        $doubanImg = $infos[0]['img'];

        $doubanName = str_replace($arrxx1, $arrdx1, $doubanName);
        $doubanName = str_replace(' ', '', $doubanName);


        $vod['vod_name'] = $doubanName;
        $vod['vod_douban_id'] = $doubanId;
        $vod['vod_pic'] = $doubanImg;

        $score = M('Vod')->where('vod_douban_id=\''.$doubanId.'\'')->getField('vod_douban_score');
        if($score && $score>0){
            $vod['vod_douban_score'] = $score;
            return $vod;
        }

        $detailHtml = ff_file_get_contents($doubanDetailUrl.$doubanId.'/');

        $hasmc = preg_match("#class=\"year\">\((\d+?)\)#i",$detailHtml,$mc);
        if($hasmc){
            $doubanYear = $mc[1];
            $vod['vod_year'] = $doubanYear>date('Y')?date("Y"):$doubanYear;
        }

        $hasmc = preg_match_all("#rel=\"v:directedBy\">(.+?)</a>#i",$detailHtml,$mc);
        if($hasmc){
            $doubanDirectors = implode(',',$mc[1]);
            $vod['vod_director'] = $doubanDirectors;
        }

        $hasmc = preg_match_all("#rel=\"v:starring\">(.+?)</a>#i",$detailHtml,$mc);
        if($hasmc){
            $doubanActors = implode(',', $mc[1] );
            $vod['vod_actor'] = $doubanActors;
        }

        $hasmc = preg_match_all("#property=\"v:genre\">(.+?)</span>#i",$detailHtml,$mc);
        if($hasmc){
            $doubanGenres = implode(',', $mc[1] );
            $vod['vod_type'] = $doubanGenres;
        }

        $hasmc = preg_match("#制片国家/地区:</span>(.+?)<br/>#i",$detailHtml,$mc);
        if($hasmc){
            $doubanArea = $mc[1];
            $vod['vod_area'] = $doubanArea;
        }

        $hasmc = preg_match("#语言:</span>(.+?)<br/>#i",$detailHtml,$mc);
        if($hasmc){
            $doubanLanguages = str_replace('/',',', $mc[1]);
            $vod['vod_language'] = $doubanLanguages;
        }

        $hasmc = preg_match("#property=\"v:initialReleaseDate\" content=\"(.+?)\">#i",$detailHtml,$mc);
        if($hasmc){
            $doubanPublishDate = mb_substr($mc[1],0,10);
            if($doubanPublishDate) {
                if(strlen($doubanPublishDate)==4){
                    $doubanPublishDate = $doubanPublishDate.'-01-01';
                }
                $vod['vod_filmtime'] = strtotime($doubanPublishDate);
            }
        }

        $hasmc = preg_match("#property=\"v:runtime\" content=\"(\d+?)\">#i",$detailHtml,$mc);
        if($hasmc){
            $doubanRuntime = $mc[1];
            $vod['vod_length'] = $doubanRuntime*60;
        }

        $hasmc = preg_match("#又名:</span>(.+?)<br/>#i",$detailHtml,$mc);
        if($hasmc){
            $doubanOthername = $mc[1];
            $vod['vod_title'] = $doubanOthername;
        }
        $hasmc = preg_match("#property=\"v:average\">(.+?)</strong>#i",$detailHtml,$mc);
        if($hasmc){
            $doubanRate = $mc[1];
            $vod['vod_douban_score'] = $doubanRate;
        }

        $hasmc = preg_match_all("#href=\"/tag/(.+?)\"#i",$detailHtml,$mc);
        if($hasmc){
            $doubanTags = implode(',', $mc[1] );
            $vod['vod_keywords'] = $doubanTags;
        }

        $hasmc = preg_match("#<span property=\"v:summary\" class=\"\">([\s\S]+?)</span>#mi",$detailHtml,$mc);
        if($hasmc){
            $doubanSummary = trim($mc[1]);
            $vod['vod_content'] = $doubanSummary;
        }

        $hasmc = preg_match_all("#class=\"short-content\">([\s\S]+?)&nbsp#mi",$detailHtml,$mc);
        if($hasmc){
            $doubanShortContents = implode('<br><br>',$mc[1]);
            $vod['vod_content'] = $vod['vod_content'].'</br></br></br>'.$doubanShortContents;
            $vod['vod_short_content'] = $doubanShortContents;
        }
        return $vod;

    }
	//xml资源库播放地址格式化
	private function vod_xml_replace($playurl){
		$array_url = array();
		$arr_ji = explode('#',str_replace('||','//',$playurl));
		foreach($arr_ji as $key=>$value){
			$urlji = explode('$',$value);
			if( count($urlji) > 1 ){
				$array_url[$key] = $urlji[0].'$'.trim($urlji[1]);
			}else{
				$array_url[$key] = trim($urlji[0]);
			}
		}
		return implode(chr(13),$array_url);
	}
	/*----------------------------------------------------------user---------------------------------------------------------------------------*/
	public function user_json($admin, $params){
		$params['g'] = 'plus';
		$params['m'] = 'api';
		$params['a'] = 'user';
		$params['p'] = $admin['page'];
		$params['key'] = $admin['apikey'];
		ksort($params);
		$url = base64_decode($admin['xmlurl']).'?'.http_build_query($params);
		$html = ff_file_get_contents($url);
		//是否采集到数据
		if(!$html){
			return array('status'=>601, 'infos'=>'连接API资源库失败，通常为服务器网络不稳定或禁用了采集。');
		}
		//数据包验证
		$json = json_decode($html, true);
		if( is_null($json) ){
			return array('status'=>602, 'infos'=>'JSON格式不正确，不支持采集。');
		}
		//资源库返回的状态501 502 503
		if($json['status'] != 200){
			return array('status'=>$json['status'], 'infos'=>$json['data']);
		}
		//返回正确的数据集合
		return array('status'=>200, 'infos'=>$json);
	}
	public function user_update($admin, $params, $json){
		echo'<style type="text/css">
			ul{margin:0 auto; width:60%;border:1px solid #666;}
			h5{text-align:center;}
			li{font-size:12px;color:#333;line-height:21px}
			li.p{color:#666;list-style:none;}
			span{font-weight:bold;color:#FF0000}
			</style><ul>
			<h5>API用户采集 共有<span>'.$json['page']['recordcount'].'</span>个数据，需要采集<span>'.$json['page']['pagecount'].'</span>次，正在执行第<span color=green>'.$admin['page'].'</span>次采集任务，每一次采集<span>'.$json['page']['pagesize'].'</span>个。
			</h5>';
		foreach($json['data'] as $key=>$user){
			echo '<li>第<span>'.(($admin['page']-1)*$json['page']['pagesize']+$key+1).'</span>个用户 '.$user['user_name'].'</li>';
			$this->user_db($user);
			ob_flush();flush();
		}
		//是否分页采集
		$admin['g'] = 'admin';
		$admin['m'] = 'cj';
		$admin['a'] = 'apis';
		$admin['page'] = 'FFLINK';
		$page_link = '?'.http_build_query(array_merge($admin, $params));
		$this->jump($json['page']["pageindex"], $json['page']['pagecount'], $page_link);
		echo'</ul>';
	}
	private function user_db($user){
		unset($user["user_id"]);
		if(empty($user['user_name'])){
			echo('<li class="p">用户名为空，不做处理!</li>');
			return false;
		}
		$array = M('User')->field('user_id,user_name')->where('user_name="'.$user['user_name'].'"')->find();
		if(!$array){
			$user['user_pwd'] = md5(time());
			$user['user_jointime'] = time();
			$user['user_logtime'] = time();
			$user['user_logip'] = get_client_ip();
			$id = M('User')->data($user)->add();
			if($id){
				echo('<li class="p">用户添加成功，'.$user['user_name'].'（'.$id.'）</li>');
			}else{
				echo('<li class="p">用户添加失败，'.M('User')->getDbError().'</li>');
			}
		}else{
			echo('<li class="p">用户名已存在，不做处理!</li>');
		}
	}
	/*----------------------------------------------------------forum---------------------------------------------------------------------------*/
	public function forum_json($admin, $params){
		$params['g'] = 'plus';
		$params['m'] = 'api';
		$params['a'] = 'forum';
		$params['p'] = $admin['page'];
		$params['key'] = $admin['apikey'];
		ksort($params);
		$url = base64_decode($admin['xmlurl']).'?'.http_build_query($params);
		$html = ff_file_get_contents($url);
		//是否采集到数据
		if(!$html){
			return array('status'=>601, 'infos'=>'连接API资源库失败，通常为服务器网络不稳定或禁用了采集。');
		}
		//数据包验证
		$json = json_decode($html, true);
		if( is_null($json) ){
			return array('status'=>602, 'infos'=>'JSON格式不正确，不支持采集。');
		}
		//资源库返回的状态501 502 503
		if($json['status'] != 200){
			return array('status'=>$json['status'], 'infos'=>$json['data']);
		}
		//返回正确的数据集合
		return array('status'=>200, 'infos'=>$json);
	}
	public function forum_update($admin, $params, $json){
		echo'<style type="text/css">
			ul{margin:0 auto; width:60%;border:1px solid #666;}
			h5{text-align:center;}
			li{font-size:12px;color:#333;line-height:21px}
			li.p{color:#666;list-style:none;}
			li.red{color:#FF0000}
			li.blue{color:blue}
			span{font-weight:bold;color:#FF0000}
			</style><ul>
			<h5>API评论采集 共有<span>'.$json['page']['recordcount'].'</span>个数据，需要采集<span>'.$json['page']['pagecount'].'</span>次，正在执行第<span color=green>'.$admin['page'].'</span>次采集任务，每一次采集<span>'.$json['page']['pagesize'].'</span>个。
			</h5>';
		foreach($json['data'] as $key=>$forum){
			echo '<li>第<span>'.(($admin['page']-1)*$json['page']['pagesize']+$key+1).'</span>个评论</li>';
			echo '<li class="p">'.$forum['forum_content'].'</li>';
			if(!$forum['forum_referer']){
				$forum['forum_referer'] = $admin['cjid'].'_'.$forum['forum_id'];
			}
			$this->forum_db($forum);
			ob_flush();flush();
		}
		//是否分页采集
		$admin['g'] = 'admin';
		$admin['m'] = 'cj';
		$admin['a'] = 'apis';
		$admin['page'] = 'FFLINK';
		$page_link = '?'.http_build_query(array_merge($admin, $params));
		$this->jump($json['page']["pageindex"], $json['page']['pagecount'], $page_link);
		echo'</ul>';
	}
	public function forum_db($forum){
		unset($forum["forum_id"]);
		if(empty($forum['forum_content'])){
			echo('<li class="p">评论内容为空，不做处理!</li>');
			return false;
		}
		$array = M('Forum')->field('forum_id')->where('forum_referer="'.$forum['forum_referer'].'"')->find();
		if($array){
			echo('<li class="p red">评论已存在，不做处理!</li>');
			return false;
		}

		$likename = trim(mb_substr($forum['vod_name'],0,4));
		$vod= M('Vod')->field('vod_id')->where('vod_name like "%'.$likename.'%"')->find();
		if($vod){
		    // 不再提交baidu
            //ff_push_url_to_baidu(array('http://www.ffilmer.com/video/detail/'.$vod['vod_id'].'.html'));

			unset($forum['forum_name']);
			unset($forum['forum_reurl']);
			$forum['forum_status'] = 1;
			$forum['forum_cid'] = $vod['vod_id'];
			$forum['forum_sid'] = 1;
			$forum['forum_uid'] = mt_rand(1, C('collect_forum'));
			$forum['forum_addtime'] = time()-rand(100000,999999);
			$forum['forum_ip'] = get_client_ip();
			$id = M('Forum')->data($forum)->add();
			if($id){
				echo('<li class="p blue">评论添加成功，（'.$id.'）</li>');
			}else{
				echo('<li class="p red">评论添加失败，'.M('Forum')->getDbError().'</li>');
			}
		}else{
			echo('<li class="p red">无对应的视频名称《'.$forum['vod_name'].'》，不做处理！</li>');
		}
	}

	/*----------------------------------------------------------scenario---------------------------------------------------------------------------*/
	public function scenario_json($admin, $params){
		$params['g'] = 'plus';
		$params['m'] = 'api';
		$params['a'] = 'scenario';
		$params['p'] = $admin['page'];
		$params['key'] = $admin['apikey'];
		ksort($params);
		$url = base64_decode($admin['xmlurl']).'?'.http_build_query($params);
		$html = ff_file_get_contents($url);
		//是否采集到数据
		if(!$html){
			return array('status'=>601, 'infos'=>'连接API资源库失败，通常为服务器网络不稳定或禁用了采集。');
		}
		//数据包验证
		$json = json_decode($html, true);
		if( is_null($json) ){
			return array('status'=>602, 'infos'=>'JSON格式不正确，不支持采集。');
		}
		//资源库返回的状态501 502 503
		if($json['status'] != 200){
			return array('status'=>$json['status'], 'infos'=>$json['data']);
		}
		//返回正确的数据集合
		return array('status'=>200, 'infos'=>$json);
	}
	public function scenario_update($admin, $params, $json){
		echo'<style type="text/css">
			ul{margin:0 auto; width:60%;border:1px solid #666;}
			h5{text-align:center;}
			li{font-size:12px;color:#333;line-height:21px}
			li.p{color:#666;list-style:none;}
			span{font-weight:bold;color:#FF0000}
			</style><ul>
			<h5>API剧情采集 共有<span>'.$json['page']['recordcount'].'</span>个数据，需要采集<span>'.$json['page']['pagecount'].'</span>次，正在执行第<span color=green>'.$admin['page'].'</span>次采集任务，每一次采集<span>'.$json['page']['pagesize'].'</span>个。
			</h5>';
		foreach($json['data'] as $key=>$scenario){
			echo '<li>第<span>'.(($admin['page']-1)*$json['page']['pagesize']+$key+1).'</span>个剧情 '.$scenario['vod_name'].'</li>';
			$this->scenario_db($scenario);
			ob_flush();flush();
		}
		//是否分页采集
		$admin['g'] = 'admin';
		$admin['m'] = 'cj';
		$admin['a'] = 'apis';
		$admin['page'] = 'FFLINK';
		$page_link = '?'.http_build_query(array_merge($admin, $params));
		$this->jump($json['page']["pageindex"], $json['page']['pagecount'], $page_link);
		echo'</ul>';
	}
	private function scenario_db($scenario){
		if(empty($scenario['vod_scenario'])){
			echo('<li class="p">剧情为空，不做处理!</li>');
			return false;
		}
		//优先从来源标识更新
		if($scenario['vod_name']){
            $array = M('Vod')->field('vod_id,vod_name,vod_inputer,vod_scenario')->where('vod_name="'.$scenario['vod_name'].'"')->find();
		}else{
            $array = M('Vod')->field('vod_id,vod_name,vod_inputer,vod_scenario')->where('vod_reurl like "%'.$scenario['vod_reurl'].'%"')->find();
		}
		// 检测是否站长锁定
		if('feifeicms' == $array['vod_inputer']){
			echo('<li class="p">站长已锁定该影片，不更新。</li>');
			return false;
		}
		if($array){
			$scenario_old = json_decode($array['vod_scenario'],true);
			if(count($scenario["vod_scenario"]['info']) > count($scenario_old['info'])){
				$data = array();
				$data['vod_id'] = $array['vod_id'];
				$data['vod_scenario'] = json_encode($scenario['vod_scenario']);
				$data['vod_addtime'] = time();
				$id = M('Vod')->save($data);
				echo('<li class="p blue">剧情更新成功（'.$array['vod_id'].'）！</li>');
			}else{
				echo('<li class="p">剧情未更新（'.$array['vod_id'].'），不做处理!</li>');
			}
		}else{
			echo('<li class="p">不存在，不做处理!</li>');
		}
	}

	/*----------------------------------------------------------news---------------------------------------------------------------------------*/
	public function news_json($admin, $params){
		$params['g'] = 'plus';
		$params['m'] = 'api';
		$params['a'] = 'news';
		$params['p'] = $admin['page'];
		$params['key'] = $admin['apikey'];
		ksort($params);
		$url = base64_decode($admin['xmlurl']).'?'.http_build_query($params);
		$html = ff_file_get_contents($url);
		//是否采集到数据
		if(!$html){
			return array('status'=>601, 'infos'=>'连接API资源库失败，通常为服务器网络不稳定或禁用了采集。');
		}
		//数据包验证
		$json = json_decode($html, true);
		if( is_null($json) ){
			return array('status'=>602, 'infos'=>'JSON格式不正确，不支持采集。');
		}
		//资源库返回的状态501 502 503
		if($json['status'] != 200){
			return array('status'=>$json['status'], 'infos'=>$json['data'].$json['message']);
		}
		//返回正确的数据集合
		return array('status'=>200, 'infos'=>$json);
	}
	public function news_update($admin, $params, $json){
		echo'<style type="text/css">
			ul{margin:0 auto; width:60%;border:1px solid #666;}
			h5{text-align:center;}
			li{font-size:12px;color:#333;line-height:21px}
			li.p{color:#666;list-style:none;}
			li.red{color:#FF0000}
			li.blue{color:blue}
			span{font-weight:bold;color:#FF0000}
			</style><ul>
			<h5>文章资讯采集 共有<span>'.$json['page']['recordcount'].'</span>个数据，需要采集<span>'.$json['page']['pagecount'].'</span>次，正在执行第<span color=green>'.$admin['page'].'</span>次采集任务，每一次采集<span>'.$json['page']['pagesize'].'</span>个。
			</h5>';
		foreach($json['data'] as $key=>$news){
			echo '<li>第<span>'.(($admin['page']-1)*$json['page']['pagesize']+$key+1).'</span>个文章《'.$news['news_name'].'》</li>';
			$news['news_inputer'] = 'xml_'.$admin['cjid'];
			$this->news_db($news);
			ob_flush();flush();
		}
		//是否分页采集
		$admin['g'] = 'admin';
		$admin['m'] = 'cj';
		$admin['a'] = 'apis';
		$admin['page'] = 'FFLINK';
		$page_link = '?'.http_build_query(array_merge($admin, $params));
		$this->jump($json['page']["pageindex"], $json['page']['pagecount'], $page_link);
		echo'</ul>';
	}
	public function news_db($news){
	  if(empty($news['news_name']) || empty($news['news_content'])){
			echo '<li class="p">文章名称或文章内容为空，不做处理!</li>';
			return false;
		}
		if(!$news['news_cid']){
			echo '<li class="p">未匹配到对应栏目分类，不做处理，请先转换分类!</li>';
			return false;
		}
		// 格式化常规字符
		if(empty($news['news_remark'])){
			$news['news_remark'] = msubstr(trim($news['news_content']),0,100,false);
		}
		// 要查询检查的字段
		$field = 'news_id,news_cid,news_name,news_remark,news_content';
		// 检测文章名称是否相等(需防止同名的冲突所以增加了CID条件)
		$array = M('News')->field($field)->where('news_cid='.$news['news_cid'].' and news_name="'.$news['news_name'].'" ')->find();
		if($array){
		    $newsUrl2=array('http://www.ffilmer.com/news/detail/'.$array['news_id'].'.html');
            // ff_push_url_to_baidu($newsUrl2);
			return $this->news_db_update($news, $array);
		}
		// 添加文章开始
		unset($news['news_id']);
		if( empty($news['news_hits']) ){
			$news['news_hits'] = mt_rand(1,C('collect_hits'));
		}
		if( empty($news['news_up']) ){
			$news['news_up'] = mt_rand(1,C('collect_updown'));
		}
		if( empty($news['news_down']) ){
			$news['news_down'] = mt_rand(1,C('collect_updown'));
		}
		if( empty($news['news_gold']) ){
			$news['news_gold'] = mt_rand(1,C('collect_gold'));
		}
		if( empty($news['news_golder']) ){
			$news['news_golder'] = mt_rand(1,C('collect_golder'));
		}
		if( empty($news['news_ename']) ){
			$news['news_ename'] = ff_pinyin($news['news_name']);
		}
		if( empty($news['news_addtime']) ){
			$news['news_addtime'] = time();
		}else{
			$news['news_addtime'] = strtotime($news['news_addtime']);
		}
		// 自动下载远程海报图片
		$img = D('Img');
		$news['news_pic'] = $img->down_load($news['news_pic']);
		// 入库接口
		$id = M('News')->data($news)->add();
		// 关联多分类及TAG相关
		if($id){
		    $newsUrl = array('http://www.ffilmer.com/news/detail/'.$id.'.html');
            // ff_push_url_to_baidu($newsUrl);
			// 增加多分类
			if( $news['news_type'] ){
				D('Tag')->tag_update($id, $news["news_type"], 'news_type');
			}
			// 增加关联tag
			if( $news['news_keywords'] ){
				D('Tag')->tag_update($id, $news["news_keywords"], 'news_tag');
			}
			echo '<li class="p">文章添加成功。</li>';
			return $id;
		}
		echo '<li class="p">文章添加失败。</li>';
		return false;
  }
	private function news_db_update($news, $news_old){
		// 检测是否站长手动锁定更新
		if('feifeicms' == $news_old['news_inputer']){
			echo '<li class="p">站长手动锁定，不更新。</li>';
			return false;
		}
		$edit = array();
		if($news['news_content'] == $news_old['news_content']){
			echo '<li class="p">文章内容未变化，不需要更新。</li>';
			return false;
		}else{
			$edit['news_content'] = $news['news_content'];
		}
		// 组合更新条件及内容(以最后一次更新的库为检测依据)
		$edit['news_id'] = $news_old['news_id'];
		$edit['news_name'] = $news['news_name'];
		$edit['news_reurl'] = $news['news_reurl'];
		$edit['news_addtime'] = time();
		// 更新数据
		M('News')->data($edit)->save();
		//删除数据缓存
		if(C('cache_page_news')){
			S(md5('cache_page_news_'.$news_old['news_id']),NULL);
		}
		echo '<li class="p">文章已更新。</li>';
		return true;
	}
}
?>